﻿using System;
using System.Linq;
using JetBrains.Annotations;
using JetBrains.Application.Progress;
using JetBrains.DocumentModel;
using JetBrains.ProjectModel;
using JetBrains.ReSharper.Feature.Services.Bulbs;
using JetBrains.ReSharper.Feature.Services.LiveTemplates.Hotspots;
using JetBrains.ReSharper.Feature.Services.LiveTemplates.LiveTemplates;
using JetBrains.ReSharper.Intentions.Extensibility;
using JetBrains.ReSharper.LiveTemplates;
using JetBrains.ReSharper.Psi.Tree;
using JetBrains.TextControl;
using JetBrains.Util;
using MugenMvvmToolkit.ReSharper.Highlighting;

namespace MugenMvvmToolkit.ReSharper.ViewModels.QuickFixes
{
    [QuickFix]
    public class InvalidValidateMethodCallFix : QuickFixBase
    {
        private readonly InvalidValidateMethodCallHighlighting _highlighting;

        #region Constructors

        public InvalidValidateMethodCallFix([NotNull] InvalidValidateMethodCallHighlighting highlighting)
        {
            if (highlighting == null) throw new ArgumentNullException("highlighting");
            _highlighting = highlighting;
        }

        #endregion

        #region Overrides of QuickFixBase

        /// <summary>
        ///     Popup menu item text
        /// </summary>
        public override string Text
        {
            get { return UiResources.FixInvalidValidateMethodCall; }
        }

        /// <summary>
        ///     Executes QuickFix or ContextAction. Returns post-execute method.
        /// </summary>
        /// <returns>
        ///     Action to execute after document and PSI transaction finish. Use to open TextControls, navigate caret, etc.
        /// </returns>
        protected override Action<ITextControl> ExecutePsiTransaction(ISolution solution, IProgressIndicator progress)
        {
            return control =>
            {
                DocumentRange range = _highlighting.Literal.GetDocumentRange();
                range = new DocumentRange(range.Document,
                    new TextRange(range.TextRange.StartOffset + 1, range.TextRange.EndOffset - 1));

                var field = new TemplateField("NAME", new TextHotspotExpression(_highlighting.Properties.ToList()), 0);
                LiveTemplatesManager.Instance.TryExecuteHotspotDefault(solution, control, new HotspotInfo(field, range));
            };
        }

        /// <summary>
        ///     Check if this action is available at the constructed context.
        ///     Actions could store precalculated info in <paramref name="cache" /> to share it between different actions
        /// </summary>
        /// <returns>
        ///     true if this bulb action is available, false otherwise.
        /// </returns>
        public override bool IsAvailable(IUserDataHolder cache)
        {
            return _highlighting.IsValid();
        }

        #endregion
    }
}